package cn.edu.zzti.base.service.impl;

import java.io.Serializable;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import cn.edu.zzti.base.dao.GenericDao;
import cn.edu.zzti.base.model.BaseEntityModel;
import cn.edu.zzti.base.service.GenericManager;

/**
 * This class serves as the Base class for all other Managers - namely to hold
 * common CRUD methods that they might all use. You should only need to extend
 * this class when your require custom CRUD logic.
 * <p/>
 * <p>
 * To register this class in your Spring context file, use the following XML.
 * 
 * 
 * 
 * @param <T>
 *            a type variable
 * @param <PK>
 *            the primary key for that type
 * @author <a href="mailto:matt@raibledesigns.com">Matt Raible</a> Updated by
 *         jgarcia: added full text search + reindexing
 */
public class GenericManagerImpl<T extends BaseEntityModel, PK extends Serializable>
		implements GenericManager<T, PK> {
	/**
	 * GenericDao instance, set by constructor of child classes
	 */
	protected GenericDao<T, PK> dao;

	/**
	 * Log variable for all child classes. Uses LogFactory.getLog(getClass())
	 * from Commons Logging
	 */
	protected final Log log = LogFactory.getLog(getClass());

	public GenericManagerImpl() {
	}

	public GenericManagerImpl(GenericDao<T, PK> genericDao) {
		this.dao = genericDao;
	}

	/**
	 * {@inheritDoc}
	 */
	public boolean exists(PK id) {
		return dao.exists(id);
	}

	/**
	 * {@inheritDoc}
	 */
	public T get(PK id) {
		return dao.get(id);
	}

	/**
	 * {@inheritDoc}
	 */
	public List<T> getAll() {
		return dao.getAll();
	}

	/**
	 * {@inheritDoc}
	 */
	public void reindex() {
		dao.reindex();
	}

	/**
	 * {@inheritDoc}
	 */
	public void reindexAll(boolean async) {
		dao.reindexAll(async);
	}

	/**
	 * {@inheritDoc}
	 */
	public void remove(PK id) {
		dao.remove(id);
	}

	/**
	 * {@inheritDoc}
	 */
	public void remove(T object) {
		dao.remove(object);
	}

	/**
	 * {@inheritDoc}
	 */
	public T save(T object) {
		return dao.save(object);
	}

	/**
	 * {@inheritDoc}
	 * <p/>
	 * Search implementation using Hibernate Search.
	 */
	public List<T> search(String q, @SuppressWarnings("rawtypes") Class clazz) {
		if (q == null || "".equals(q.trim())) {
			return getAll();
		}

		return dao.search(q);
	}
}
